// 设置页面
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';

class Demo3 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 从服务器上面拿到的数据
    var listItems = [
      {'icon': Icons.access_time, 'title': '飞行模式', 'checked': false},
      {'icon': Icons.settings, 'title': 'Wi-Fi', 'checked': true},
      {'icon': Icons.favorite, 'title': '蓝牙', 'checked': true},
      {'icon': Icons.zoom_in, 'title': '移动网络', 'checked': false},
    ];

    return Column(
      children: [
        Mylist(
            listItems: listItems,
            onCheckedChanged: (item, val) {
              //这里为什么要用这个回调来改，就是遵循那个的状态 那个来改
              item['checked'] = val;
            }),
        Center(
          child: FlatButton(
            color: Colors.blue,
            child: Text('发给服务器'),
            onPressed: () {
              print(listItems);
            },
          ),
        )
      ],
    );
  }
}

// 处理数据
class Mylist extends HookWidget {
  final listItems;
  final Function onCheckedChanged;
  Mylist({Key key, this.listItems, this.onCheckedChanged}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
        children: listItems.map<ListItem>((item) {
      var checked = useState(item['checked']);
      return ListItem(
        icon: item['icon'],
        title: item['title'],
        checked: checked.value,
        onChanged: (val) {
          checked.value = val;
          onCheckedChanged(item, val);
        },
      );
    }).toList());
  }
}

// 渲染的单个页面
class ListItem extends StatelessWidget {
  final icon;
  final title;
  final checked;
  final onChanged;

  ListItem({Key key, this.icon, this.title, this.checked, this.onChanged})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(top: 10, bottom: 10, left: 20, right: 20),
      child: Row(
        children: [
          Container(
            margin: EdgeInsets.only(right: 20),
            child: Icon(icon, size: 26),
          ),
          Expanded(
            child: Text(title, style: TextStyle(fontSize: 20)),
          ),
          Switch(
            value: checked,
            onChanged: onChanged,
          )
        ],
      ),
    );
  }
}
